﻿using BleSolution;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using Windows.Devices.Bluetooth;
using YH.Bluetooth;

namespace BleSolution
{
    public partial class Form4 : Form
    {
        /// <summary>
        /// 蓝牙处理核心类
        /// </summary>
        BleCore bleCore = null;
        /// <summary>
        /// 存储检测到的设备
        /// </summary>
        List<Windows.Devices.Bluetooth.BluetoothLEDevice> DeviceList = new List<Windows.Devices.Bluetooth.BluetoothLEDevice>();
        /// <summary>
        /// 当前蓝牙服务列表
        /// </summary>
        List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattDeviceService> GattDeviceServices = new List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattDeviceService>();
        /// <summary>
        /// 当前蓝牙服务特征列表
        /// </summary>
        List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic> GattCharacteristics = new List<Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic>();

        private readonly IWebSocketServerService _webSocketServerService;
        public Form4(IWebSocketServerService webSocketServerService)
        {
            try
            {
                LogHelper.WriteLog("程序启动");
                InitializeComponent();
                _webSocketServerService = webSocketServerService;
                bleCore = new BleCore(_webSocketServerService);

                CheckForIllegalCrossThreadCalls = false;
                this.bleCore.MessAgeChanged += BleCore_MessAgeChanged;
                this.bleCore.DeviceWatcherChanged += BleCore_DeviceWatcherChanged;
                this.bleCore.GattDeviceServiceAdded += BleCore_GattDeviceServiceAdded;
                this.bleCore.CharacteristicAdded += BleCore_CharacteristicAdded;
                this.Init();
               
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 初始化界面
        /// </summary>
        private void Init()
        {
            try
            {
                this.btn_match_device.Enabled = false;
                this.btn_get_service.Enabled = false;
                this.btn_get_feature.Enabled = false;
                this.btn_listten_receive_feature.Enabled = false;
                this.btn_check_send_feature.Enabled = false;
                this.btn_send_data.Enabled = false;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 获取特征列表
        /// </summary>
        private void BleCore_CharacteristicAdded(Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristic gattCharacteristic)
        {
            try
            {
                RunAsync(() =>
                {
                    this.cmb_receive_feature_list.Items.Add(gattCharacteristic.Uuid);
                    this.cmb_send_feature_list.Items.Add(gattCharacteristic.Uuid);
                    this.GattCharacteristics.Add(gattCharacteristic);
                    this.btn_listten_receive_feature.Enabled = true;
                    this.btn_check_send_feature.Enabled = true;
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 获取蓝牙服务列表
        /// </summary>
        private void BleCore_GattDeviceServiceAdded(Windows.Devices.Bluetooth.GenericAttributeProfile.GattDeviceService gattDeviceService)
        {
            try
            {
                RunAsync(() =>
                {
                    this.cmb_service_list.Items.Add(gattDeviceService.Uuid.ToString());
                    this.GattDeviceServices.Add(gattDeviceService);
                    this.btn_get_feature.Enabled = true;
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
        /// <summary>
        /// 搜索蓝牙设备列表
        /// </summary>
        private void BleCore_DeviceWatcherChanged(MsgType type, Windows.Devices.Bluetooth.BluetoothLEDevice bluetoothLEDevice)
        {
            try
            {
                RunAsync(() =>
                {
                    this.lsb_device_list.Items.Add(bluetoothLEDevice.Name);
                    this.DeviceList.Add(bluetoothLEDevice);
                    this.btn_match_device.Enabled = true;

                    string my_name = bluetoothLEDevice.Name;
                    byte[] _Bytes1 = BitConverter.GetBytes(bluetoothLEDevice.BluetoothAddress);
                    Array.Reverse(_Bytes1);
                    string my_mac = BitConverter.ToString(_Bytes1, 2, 6).Replace('-', ':').ToLower();
                    SendFindReplyDevicesubClass my_sendFindReplyDevicesubClass = new SendFindReplyDevicesubClass();
                    my_sendFindReplyDevicesubClass.name = my_name;
                    my_sendFindReplyDevicesubClass.mac = my_mac;
                    SendFindReplyDeviceClass my_sendFindReplyDeviceClass = new SendFindReplyDeviceClass();
                    my_sendFindReplyDeviceClass.command = CommondCode.find_device_reply.ToString();
                    my_sendFindReplyDeviceClass.device = my_sendFindReplyDevicesubClass;
                    string my_send_data = JsonConvert.SerializeObject(my_sendFindReplyDeviceClass);
                    // Thread.Sleep(100);
                    _webSocketServerService.SendMessageToAllAsync(my_send_data);
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 提示消息
        /// </summary>
        private void BleCore_MessAgeChanged(MsgType type, string message, byte[] data)
        {
            try
            {
                RunAsync(() =>
                {
                    this.lsb_message_list.Items.Add(message);
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }

        // 异步线程
        public static void RunAsync(Action action)
        {
            try
            {
                ((Action)(delegate ()
                {
                    action.Invoke();
                })).BeginInvoke(null, null);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 功能：点击搜索按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_seacher_ble_device_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.btn_seacher_ble_device.Text == "搜索蓝牙设备")
                {
                    LogHelper.WriteLog("搜索蓝牙设备");
                    this.lsb_message_list.Items.Clear();
                    this.lsb_device_list.Items.Clear();
                    this.bleCore.StartBleDeviceWatcher();
                    this.btn_seacher_ble_device.Text = "停止";
                }
                else 
                {
                    LogHelper.WriteLog("停止搜索蓝牙设备");
                    this.bleCore.StopBleDeviceWatcher();
                    this.btn_seacher_ble_device.Text = "搜索蓝牙设备";
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 功能：匹配设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_match_device_Click(object sender, EventArgs e)
        {
            try
            {
                LogHelper.WriteLog("匹配蓝牙设备");
                if (this.lsb_device_list.SelectedItem != null)
                {
                    string my_deviceName = this.lsb_device_list.SelectedItem.ToString();
                    Windows.Devices.Bluetooth.BluetoothLEDevice my_bluetoothLEDevice = this.DeviceList.Where(u => u.Name == my_deviceName).FirstOrDefault();
                    if (my_bluetoothLEDevice != null) 
                    {
                        bleCore.StartMatching(my_bluetoothLEDevice);
                        this.btn_get_service.Enabled = true;
                    }
                }
                else 
                {
                    MessageBox.Show("请选择连接的蓝牙.");
                    this.btn_get_service.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 功能：点击获取服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_get_service_Click(object sender, EventArgs e)
        {
            try
            {
                LogHelper.WriteLog("点击获取服务按钮");
                this.cmb_service_list.Items.Clear();
                this.bleCore.FindService();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 功能：点击获取特征
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_get_feature_Click(object sender, EventArgs e)
        {
            try
            {
                LogHelper.WriteLog("点击获取服务特征按钮");
                this.cmb_receive_feature_list.Items.Clear();
                this.cmb_send_feature_list.Items.Clear();
                if (this.cmb_service_list.SelectedItem != null)
                {
                    var item = this.GattDeviceServices.Where(u => u.Uuid == new Guid(this.cmb_service_list.SelectedItem.ToString())).FirstOrDefault();
                    this.bleCore.FindCharacteristic(item);
                }
                else
                {
                    MessageBox.Show("选择蓝牙服务.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 功能：监听接收特征的服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btn_listten_receive_feature_Click(object sender, EventArgs e)
        {
            try
            {
                LogHelper.WriteLog("点击监听接收特征按钮");
                if (this.cmb_receive_feature_list.SelectedItem != null)
                {
                    var item = this.GattCharacteristics.Where(u => u.Uuid == new Guid(this.cmb_receive_feature_list.SelectedItem.ToString())).FirstOrDefault();
                    await this.bleCore.SetReceiveOpteron(item);
                }
                else
                {
                    MessageBox.Show("选择蓝牙服务.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 功能：设置发送特征服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_check_send_feature_Click(object sender, EventArgs e)
        {
            try
            {
                LogHelper.WriteLog("点击查看特征操作按钮");
                if (this.cmb_send_feature_list.SelectedItem != null)
                {
                    var item = this.GattCharacteristics.Where(u => u.Uuid == new Guid(this.cmb_send_feature_list.SelectedItem.ToString())).FirstOrDefault();
                    this.bleCore.SetSendOpteron(item);
                    if (item.CharacteristicProperties == (Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties.Notify | Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties.Write))
                    {
                        this.btn_send_data.Enabled = true;
                    }
                }
                else
                {
                    MessageBox.Show("选择蓝牙服务.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 功能：发送数据
        /// 86530004-43e6-47b7-9cb0-5fc21d4ae340  这个特征值
        /// 0xAA, 0x01, 0xD1, 0x21, 0xBB
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_send_data_Click(object sender, EventArgs e)
        {
            try
            {
                LogHelper.WriteLog("点击发送数据按钮");
                byte[] dataBytes = new byte[6];

                dataBytes[0] = 0xAA;
                dataBytes[1] = 0x01;
                dataBytes[2] = 0xD1;
                dataBytes[3] = 0x21;
                dataBytes[4] = 0xBB;

                this.bleCore.Write(dataBytes);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 清空列表
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_clear_list_msg_Click(object sender, EventArgs e)
        {
            try
            {
                LogHelper.WriteLog("点击清空列表按钮");
                RunAsync(() =>
                {
                    this.lsb_message_list.Items.Clear();
                });
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
        }

        private void btnOpteron_Click(object sender, EventArgs e)
        {
            try
            {
                if (this.cmb_receive_feature_list.SelectedItem != null)
                {
                    var item = this.GattCharacteristics.Where(u => u.Uuid == new Guid(this.cmb_receive_feature_list.SelectedItem.ToString())).FirstOrDefault();
                    this.bleCore.SetOpteron(item);
                    //if (item.CharacteristicProperties == (Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties.Notify | Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties.Read | Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties.Write))
                    //{
                    //    this.btnReader.Enabled = true;
                    //    this.btnSend.Enabled = true;
                    //}
                    if (item.CharacteristicProperties == (Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties.Notify | Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties.Write))
                    {
                        //this.btnSend.Enabled = true;
                    }
                    if (item.CharacteristicProperties == (Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties.Notify | Windows.Devices.Bluetooth.GenericAttributeProfile.GattCharacteristicProperties.Read))
                    {
                        //this.btnReader.Enabled = true;
                    }

                }
                else
                {
                    MessageBox.Show("选择蓝牙服务.");
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                /// <summary>
                /// 解析数据的类
                /// </summary>
                SLPWrapper slp = new SLPWrapper();
                //this.bleCore.StopReceive();
                Console.WriteLine($"初始化结果: {slp.InitializeSLP()}");

                // 准备测试数据
                var eegData = Enumerable.Range(1, 270).Select(j => (float)j).ToArray();
                var accX = Enumerable.Range(1, 10).Select(j => 0.1f * j).ToArray();
                var accY = Enumerable.Range(1, 100).Select(j => 0.2f * j).ToArray();
                var accZ = Enumerable.Range(1, 100).Select(j => 0.3f * j).ToArray();

                Console.WriteLine("数据准备完成，开始调用计算...");
                Console.WriteLine($"计算结果: {slp.CalculateSLP(eegData, accX, accY, accZ, 1050.0f)}");
                Console.WriteLine($"清理结果: {slp.DestroySLP()}");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                this.bleCore.SstartReceive();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private Task _serverTask;
        /// <summary>
        /// 打开wbsocket服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private  void btn_open_wbsocket_service_Click(object sender, EventArgs e)
        {
            try
            {
                if (_serverTask == null || _serverTask.IsCompleted)
                {
                    _serverTask = WebSocketServer.StartAsync();
                    MessageBox.Show("WebSocket 服务器正在启动...");
                }
                else
                {
                    MessageBox.Show("WebSocket 服务器已经在运行！");
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
        }
        /// <summary>
        /// 关闭wbsocket服务
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_close_wbsocket_service_Click(object sender, EventArgs e)
        {
            try
            {
                if (_serverTask != null && !_serverTask.IsCompleted)
                {
                    WebSocketServer.Stop();
                    MessageBox.Show("WebSocket 服务器正在停止...");
                }
                else
                {
                    MessageBox.Show("WebSocket 服务器未运行！");
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
        }
        private Task _serverTask2;
        private void button4_Click(object sender, EventArgs e)
        {
            try
            {
                if (_serverTask2 == null || _serverTask2.IsCompleted)
                {
                    _serverTask2 = _webSocketServerService.StartAsync();
                    MessageBox.Show("WebSocket 服务器正在启动...");
                }
                else
                {
                    MessageBox.Show("WebSocket 服务器已经在运行！");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            try
            {
                if (_serverTask2 != null && !_serverTask2.IsCompleted)
                {
                    _webSocketServerService.Stop();
                    MessageBox.Show("WebSocket 服务器正在停止...");
                }
                else
                {
                    MessageBox.Show("WebSocket 服务器未运行！");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }

        }

        private void Form4_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                WebSocketServer.Stop();
                _webSocketServerService.Stop();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }

        private void Form4_Load(object sender, EventArgs e)
        {
            try
            {
                //获取程序的启动路径
                string my_str_StartPath = System.Windows.Forms.Application.StartupPath;
                string my_str_iniPath = my_str_StartPath + "\\ini\\ini.xml";
                try
                {
                    XmlTextReader rdr = new XmlTextReader(my_str_iniPath);
                    while (rdr.Read())
                    {
                        if (rdr.NodeType == XmlNodeType.Element)
                        {
                            //通过rdr.Name得到节点名
                            string elementName = rdr.Name;
                            if (elementName == "root")
                            {
                            }
                            else if (elementName == "service_port")
                            {
                                //可以通过中括号获得属性值
                                //string colorVal = rdr["color"];
                                //读取到节点内文本内容
                                if (rdr.Read())
                                {
                                    //通过rdr.Value获得文本内容
                                    string my_service_port = rdr.Value;
                                    int my_int_service_port = 8080;
                                    if (int.TryParse(my_service_port, out my_int_service_port))
                                    {

                                    }
                                    InfoClass.servicePort = my_int_service_port;
                                }
                            }

                        }
                        else if (rdr.NodeType == XmlNodeType.EndElement)
                        {
                            //在节点结束时也可以通过rdr.Name获得节点名字
                            //string elementName = rdr.Name;
                            //Console.WriteLine(elementName + " element end");
                        }
                    }
                }
                catch (Exception ex)
                {
                    //输出日志
                    LogHelper.WriteLog("读取配置文件发生异常-》" + ex);
                }

            }
            catch (Exception ex)
            {
                LogHelper.WriteLog(ex);
            }
        }
    }
}
